<template>
  <div class="container">
    <div id="map"></div>
  </div>
</template>

<script>
import 'mapbox-gl/dist/mapbox-gl.css'
import mapboxgl from 'mapbox-gl' // or "const mapboxgl = require('mapbox-gl');"
import { drawCanvas } from '../../src/utils/dataUtils'
export default {
  name: 'Vue2MapboxMapTemplate',
  data () {
    return {}
  },

  mounted () {
    this.initMap()
  },

  methods: {
    initMap () {
      mapboxgl.accessToken =
        'pk.eyJ1IjoiY3Vpaml5aW5nIiwiYSI6ImNsZ3QyZjY4ODAxbDEza3BkOTJqbTJvN3gifQ.Ldj9qAFzb5uzcLP-VtFB3A'
      const map = new mapboxgl.Map({
        container: 'map', // container ID
        style: 'mapbox://styles/cuijiying/cll09l2nz007w01picbmj3e1z', // style URL
        center: [118.79013542048335, 32.05775855185749], // starting position [lng, lat]
        // center: mapboxgl.MercatorCoordinate.fromLngLat([118.79013542048335,32.05775855185749]), // starting position [lng, lat]
        zoom: 5, // starting zoom
        projection: 'mercator'
      })

      //
      map.on('click', 'earthquakes-layer', (evt) => {
        console.log(evt.features[0])
      })

      map.on('load', (e) => {
        //  let layers = map.getStyle().layers;
        //  console.log(layers, 'llllllllllllll');

        drawCanvas().forEach(item => {
          map.loadImage(
            // 'https://s2.cn.bing.net/th?id=OJ.AR0cTRmf9y09BQ&w=120&h=120&c=8&rs=1&pid=academic',
            item.imgUrl,
            function (error, image) {
              if (error) throw error
              map.addImage(item.id, image)
            }
          )
        })

        // const datas = {
        //   colorZoom: [0, 2, 4, 6],
        //   colors: ['0,255,0', '0,0,255', '255,0,0']
        // }

        // const stepLend = this.draw(map, datas)

        const dataGEos = [
          { type: 'Feature', properties: { id: 'ak16994521', mag: 2.3, time: 1507425650893, felt: 'null', tsunami: 0 }, geometry: { type: 'Point', coordinates: [121.5129, 33.1016, 0.0] } },
          { type: 'Feature', properties: { id: 'ak16994519', mag: 1.7, time: 1507425289659, felt: '1', tsunami: 0 }, geometry: { type: 'Point', coordinates: [120.4048, 33.1224, 105.5] } },
          { type: 'Feature', properties: { id: 'ak16994517', mag: 1.6, time: 1507424832518, felt: '3', tsunami: 0 }, geometry: { type: 'Point', coordinates: [121.3597, 23.0781, 0.0] } },
          { type: 'Feature', properties: { id: 'ci38021336', mag: 1.42, time: 1507423898710, felt: 'null', tsunami: 0 }, geometry: { type: 'Point', coordinates: [118.497, 24.299667, 7.64] } }]

        // dataGEos =  dataGEos.map(item =>{
        //   item.felt = item.felt === null?null:Number(item.felt)
        //   // item.felt = item.felt === null?null:item.felt
        //   return item;
        // })

        // console.log(dataGEos,'dataGEos============');

        map.addSource('earthquakes', {
          type: 'geojson',
          // Use a URL for the value for the `data` property.
          // data: "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
          data: {
            type: 'FeatureCollection',
            features: dataGEos
          }
        })

        map.addLayer({
          id: 'earthquakes-layer',
          type: 'symbol',
          source: 'earthquakes',
          layout: {
            // "icon-image": stepLend,
            // "icon-image":
            // [
            //   "match",
            //   ["get", "mag"],
            //   3, "rect",
            //   "tri"
            // ],
            // "icon-image": [
            //   "step",
            //   ["get", "mag"], // 替换为您的属性字段名
            //   '2',
            //   2,
            //   "4", // 默认图标名称
            //   4,
            //   "6"
            // ],

            // "icon-image": [
            //   "case",
            //   // ["<", ["get", "mag"], 2],
            //   ["all", [">", ["get", "felt"], 0], ["<=", ["get", "felt"], 2]],
            //   "tri",
            //   // ["<", ["get", "mag"], 4],
            //   ["all", [">", ["get", "felt"], 2], ["<", ["get", "mag"], 4]],
            //   "rect",
            //   ["==", ["get", "felt"], 4],
            //   "star",
            //   "rect-grey" // 默认图标 ==null没有生效
            // ],

            // "icon-image": [
            //   "case",
            //   // ["has", "magun"],
            //   ["has", "mag"],
            //   [
            //     "case",
            //     ["all", [">=", ["get", "mag"], 0], ["<", ["get", "mag"], 2]],
            //     "rect",
            //     ["all", [">=", ["get", "mag"], 2], ["<", ["get", "mag"], 4]],
            //     "tri",
            //     "star"
            //   ],
            //   ["==", ["get", "felt"], null], 'rect-grey',
            //   "rect-grey" // 默认图标
            // ],
            'icon-image': [
              'match',
              ['get', 'felt'],
              'null', 'rect-grey', // 默认图标
              [
                'case',
                ['all', ['>=', ['to-number', ['get', 'felt']], 0], ['<', ['to-number', ['get', 'felt']], 2]],
                'rect',
                ['all', ['>=', ['to-number', ['get', 'felt']], 2], ['<', ['to-number', ['get', 'felt']], 4]],
                'tri',
                'star'
              ]
            ],
            'icon-size': 1.0,
            // "icon-allow-overlap": true,
            'text-field': '{felt}',
            // 'symbol-sort-key':['get', 'mag'], // 设置 symbol-sort-key
            // 'symbol-sort-key':
            // [
            //   "case",
            //   [">", ["get", "mag"], 0], // 如果 sort_key 小于 0
            //   ["*", ["get", "mag"], -1], // 将 sort_key 取反
            //   ["get", "mag"] // 否则保持原值
            // ], // 设置 symbol-sort-key
            'symbol-sort-key': ['*', ['get', 'felt'], -1], // 将 sort_key 取反
            'text-anchor': 'top',
            'text-offset': [0, 0.3]
          }
        })
      })
    },
    draw (map, datas) {
      const canvas = document.createElement('canvas')
      canvas.width = 15
      canvas.height = 15
      const context = canvas.getContext('2d')

      context.beginPath()
      context.moveTo(7, 0)
      context.lineTo(0, 15)
      context.lineTo(15, 15)
      context.closePath()

      const resArr = ['step', ['get', 'mag']]
      datas.colors.forEach((item, index) => {
        // const color = item.split(',')

        // const width = 16; // The image will be 64 pixels square
        // const bytesPerPixel = 4; // Each pixel is represented by 4 bytes: red, green, blue, and alpha.
        // const data = new Uint8Array(width * width * bytesPerPixel);
        // for (let x = 0; x < width; x++) {
        //   for (let y = 0; y < width; y++) {
        //     const offset = (y * width + x) * bytesPerPixel;
        //     data[offset + 0] = color[0]; // red
        //     data[offset + 1] = color[1]; // green
        //     data[offset + 2] = color[2]; // blue
        //     data[offset + 3] = 200; // alpha
        //   }
        // }

        // context.fillStyle = "red"; // 设置三角形的颜色
        context.fillStyle = `rgb(${item})` // 设置三角形的颜色
        context.fill()

        const nameIcon = datas.colorZoom[index + 1]
        console.log(nameIcon)
        // map.addImage(nameIcon+'', { width: width, height: width, data: data });
        map.addImage(nameIcon + '', { width: 15, height: 15, data: context.getImageData(0, 0, 15, 15).data })
        resArr.push(nameIcon + '', datas.colorZoom[index + 1])
      })
      // resArr.pop()
      console.log(resArr)
      console.log(map.listImages(), 'const allImages = map.listImages();')
      return resArr
    }
  }
}
</script>

<style></style>
